<template>
  <div class="containerBox">
    <el-form  label-width="110px" :model="dataForm" :rules="dataRules" ref="dataForm">
      <el-form-item prop="goodsName" label="商品名称">
        <el-input  v-model="dataForm.goodsName" placeholder="单行输入"></el-input>
      </el-form-item>
      <el-form-item prop="goodsClass" label="商品分类">
        <div class="goodClass" v-for="(item, index) in dataForm.goodsClass" :key="index">
          <span>一级分类</span>
          <el-select v-model="item.firstClass">
            <el-option value="DOG" label="狗"></el-option>
            <el-option value="CUT" label="猫"></el-option>
          </el-select>
          <span>二级分类</span>
          <el-select v-model="item.secondClass">
            <el-option value="ZHULAING" label="主粮"></el-option>
            <el-option value="LINGSHI" label="零食"></el-option>
          </el-select>
          <span>三级分类</span>
          <el-select v-model="item.thirdClass">
            <el-option value="CNZHULAING" label="国产主粮" ></el-option>
            <el-option value="JKZHULAING" label="进口主粮" ></el-option>
          </el-select>
        </div>
        <el-button class="addClass" @click="addSomthing('addClass')">添加分类</el-button>
      </el-form-item>
      <el-form-item prop="specifications" label="商品规格">
        <div class="specB" v-for="(item, index) in dataForm.specifications" :key="'01' + index">
          <el-form-item label="规格名称">
            <el-input :disabled="item.editOff" v-model="item.specName"></el-input>
          </el-form-item>
          <el-form-item label="规格值">
            <span class="specVal" v-for="(items, index) in item.specValS" :key="'03' + index">
            {{items.specVal}}
              <i class="delBtn hover" v-if="!item.editOff" @click="addSomthing('delVal',index, item)">-</i>
            </span>
            <p class="addBtn" v-if="!item.editOff">
              <el-input value="" v-model="specValue"></el-input>
              <el-button @click="addSomthing('addSpecVal', index)">添加</el-button>
            </p>
          </el-form-item>
          <p class="operations">
            <a class="editSpec" v-if="item.editOff" @click="addSomthing('editSpec',index, item)">编辑</a>
            <a class="sureAddSpec" v-if="!item.editOff" @click="addSomthing('sureAddSpec',index, item)">确定添加此规格</a>
            <a class="delSpec" v-if="dataForm.specifications.length > 1" @click="addSomthing('delSpec',index, item)">删除</a>
          </p>
        </div>
        <el-button class="addClass" @click="addSomthing('addSpec')">添加规格</el-button>
      </el-form-item>
      <el-form-item prop="priceInventory" label="价格库存"  class="tableList">
        <el-table
          ref="multipleTable"
          :data="dataForm.priceInventory"
          tooltip-effect="dark"
          style="width: 100%"
        >
          <el-table-column prop="goodsCode" label="价格（元）"></el-table-column>
          <el-table-column prop="goodsCode" label="划线价（元）"></el-table-column>
          <el-table-column prop="goodsCode" label="库存"></el-table-column>
          <el-table-column prop="goodsCode" label="商品条形码"></el-table-column>
          <el-table-column prop="goodsCode" label="规格图片"></el-table-column>
          <el-table-column prop="goodsCode" label="运费设置（元）"></el-table-column>
        </el-table>
      </el-form-item>
      <el-form-item prop="tagNameId" label="商品标签">
        <div class="tags">
          <span>标签组</span>
          <el-select v-model="chooseTagDate1.tagNameId" @change="changeId1" placeholder="请选择">
            <el-option
              v-for="item in goodTagDate1"
              :key="item.tagId"
              :label="item.tagName"
              :value="item.tagId">
            </el-option>
          </el-select>
          <span>标签内容</span>
          <el-select v-model="chooseTagDate2.tagValId" @change="changeId2" placeholder="请选择">
            <el-option
              v-for="item in goodTagDate2"
              :key="item.tagId"
              :label="item.tagName"
              :value="item.tagId">
            </el-option>
          </el-select>
          <el-button @click="addSomthing('addTag')">添加标签</el-button>
        </div>
        <span class="specVal" v-for="(item, index) in dataForm.goodsTags" :key="item.tagValId">
          {{item.tagVal}} <i class="delBtn" @click="addSomthing('delTagVal', index, item)">-</i>
        </span>
      </el-form-item>
      <el-form-item prop="goodsMainPictures" label="商品主图">
        <el-upload
          action="https://jsonplaceholder.typicode.com/posts/"
          multiple
          list-type="picture-card"
          :on-preview="handlePictureCardPreview"
          :before-upload="beforeAvatarUpload1"
          :on-success="successUpload"
          :on-error="errorUpload"
        >
          <i class="el-icon-plus"></i>
        </el-upload>
        <el-dialog :visible.sync="dialogVisible">
          <img width="100%" :src="dialogImageUrl" alt="">
        </el-dialog>
      </el-form-item>
      <el-form-item prop="goodsDetailPicture" label="商品详情">
        <el-upload
          class="avatar-uploader"
          action="https://jsonplaceholder.typicode.com/posts/"
          :show-file-list="false"
          :on-success="handleAvatarSuccess"
          :before-upload="beforeAvatarUpload2"
          :on-error="errorUpload"
        >
          <div class="flex">
            <img v-if="imageUrl" :src="imageUrl" class="avatar">
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </div>
        </el-upload>
      </el-form-item>
      <el-form-item prop="isUpperShelf" label="是否上架">
        <el-radio v-model="dataForm.isUpperShelf" label="YES">立即上架</el-radio>
        <el-radio v-model="dataForm.isUpperShelf" label="NO">放入仓库</el-radio>
      </el-form-item>
      <el-button @click="submitForm">发布</el-button>
    </el-form>
  </div>
</template>

<script>
export default {
  name: 'goodsRelease',
  data () {
    return {
      // 主图
      dialogVisible: false,
      dialogImageUrl: '',
      // 详情图
      imageUrl: '',
      couldAddSpec: true,
      specValue: '',
      dataForm: {
        goodsName: '',
        goodsClass: [
          // {
          //   firstClass: '',
          //   secondClass: '',
          //   thirdClass: ''
          // }
        ],
        specifications: [
          // {
          //   specName: '口味',
          //   specVal: ['羊肉', '鸡肉', '鸭肉'],
          //   editOff: true
          // }, {
          //   specName: '重量',
          //   specVal: ['1kg', '2kg', '5kg'],
          //   editOff: true
          // }
          // {
          //   specName: '口味',
          //   id: 888,
          //   editOff: true,
          //   specValS: [
          //     {
          //       specVal: '羊肉味',
          //       key: 100
          //     }, {
          //       specVal: '鸡肉味',
          //       key: 200
          //     }, {
          //       specVal: '鸭肉味',
          //       key: 300
          //     }
          //   ]
          // }, {
          //   specName: '形状',
          //   id: 999,
          //   editOff: true,
          //   specValS: [
          //     {
          //       specVal: '圆形',
          //       key: 400
          //     }, {
          //       specVal: '三角形',
          //       key: 500
          //     }
          //   ]
          // }
        ],
        priceInventory: null,
        goodsTags: [],
        goodsMainPictures: [],
        goodsDetailPicture: null,
        isUpperShelf: 'YES'
      },
      dataRules: {
        goodsName: [
          { required: true, message: '请输入商品名称', trigger: 'blur' }
        ],
        goodsClass: [
          { required: true, message: '请输入商品名称', trigger: 'blur' }
        ],
        specifications: [
          { required: true, message: '请输入商品名称', trigger: 'blur' }
        ],
        goodsTags: [
          { required: true, message: '请输入活动名称', trigger: 'blur' }
        ],
        goodsMainPictures: [
          { required: true, message: '请输入活动名称', trigger: 'blur' }
        ],
        goodsDetailPicture: [
          { required: true, message: '请输入活动名称', trigger: 'blur' }
        ]
      },
      goodTagDate1: [
        {
          tagName: '国产主粮',
          tagId: 1
        }, {
          tagName: '国产猫粮',
          tagId: 2
        }
      ],
      goodTagDate2: [
        {
          tagName: '全犬',
          tagId: 10
        }, {
          tagName: '幼犬',
          tagId: 11
        }, {
          tagName: '成犬',
          tagId: 12
        }
      ],
      chooseTagDate1: {
        // 选取标签组id  获取标签内容
        tagName: '',
        tagNameId: null
      },
      chooseTagDate2: {
        tagVal: '',
        tagValId: null
      }
    }
  },
  methods: {
    addSomthing (type, index, item) {
      if (type === 'addClass') {
        // 添加分类
        let newClass = {
          firstClass: '',
          secondClass: '',
          thirdClass: ''
        }
        this.dataForm.goodsClass.push(newClass)
      } else if (type === 'addSpecVal') {
        // 添加规格值
        let newVal = {
          specVal: this.specValue,
          key: 400
        }
        if (newVal.specVal === '') return false
        this.dataForm.specifications[index].specValS.push(newVal)
        this.specValue = ''
      } else if (type === 'addSpec') {
        // 添加规格
        if (!this.couldAddSpec) return false
        let newSpec = {
          specName: '',
          editOff: false,
          specValS: []
        }
        this.dataForm.specifications.push(newSpec)
        this.couldAddSpec = false
      } else if (type === 'sureAddSpec') {
        this.specValue = ''
        // 确定添加该规格
        if (item.specName === '' || item.specValS.length === 0) {
          this.couldAddSpec = false
          return false
        } else {
          item.editOff = true
          this.couldAddSpec = true
          this.dataForm.priceInventory = this.refac(this.getSpecValSArr(this.dataForm.specifications))
          console.log(this.dataForm.priceInventory)
        }
      } else if (type === 'editSpec') {
        // 编辑规格
        this.couldAddSpec = false
        item.editOff = false
      } else if (type === 'delSpec') {
        // 删除规格
        if (!item.editOff) {
          this.couldAddSpec = true
        }
        this.dataForm.specifications.splice(index, 1)
      } else if (type === 'delVal') {
        // 删除规格值
        item.specValS.splice(index, 1)
      } else if (type === 'addTag') {
        // 添加标签
        if (this.chooseTagDate1.tagNameId !== null && this.chooseTagDate2.tagVal !== '') {
          let newTagDate = this.chooseTagDate2
          var _this = this
          if (_this.dataForm.goodsTags.length > 0) {
            var off = 0
            _this.dataForm.goodsTags.forEach((val) => {
              if (val.tagValId === newTagDate.tagValId) {
                off++
              }
            })
            if (off > 0) {
              return false
            } else {
              _this.dataForm.goodsTags.push(newTagDate)
            }
          } else {
            _this.dataForm.goodsTags.push(newTagDate)
          }
          _this.chooseTagDate2 = {
            tagVal: '',
            tagValId: null
          }
        } else {
          return false
        }
      } else if (type === 'delTagVal') {
        this.dataForm.goodsTags.splice(index, 1)
      }
    },
    changeId1 (val) {
      this.chooseTagDate1.tagNameId = val
    },
    changeId2 (callBackVal) {
      let _this = this
      this.goodTagDate2.forEach((val) => {
        if (val.tagId === callBackVal) {
          _this.chooseTagDate2.tagVal = val.tagName
        }
      })
    },
    handlePictureCardPreview (file) {
      this.dialogImageUrl = file.url
      this.dialogVisible = true
    },
    beforeAvatarUpload1 (file) {
      const isJPG = file.type === 'image/jpeg'
      const isPNG = file.type === 'image/png'
      const isLt2M = file.size / 1024 / 1024 < 2
      if (!isJPG && !isPNG) {
        this.$message.error('上传主图只能是 JPG 和 PNG 格式!')
      }
      if (!isLt2M) {
        this.$message.error('上传主图单张图片大小不能超过 2MB!请压缩')
      }
      return (isJPG || isPNG) && isLt2M
    },
    successUpload (response, file, fileList) {
      var newPicS = {
        url: file.url,
        id: response.id
      }
      this.dataForm.goodsMainPictures.push(newPicS)
    },
    errorUpload (err) {
      alert(err)
      console.log(err)
    },
    // 详情
    handleAvatarSuccess (res, file) {
      console.log(file)
      this.imageUrl = URL.createObjectURL(file.raw)
      let newPic = {
        id: file.response,
        url: this.imageUrl
      }
      this.dataForm.goodsDetailPicture = newPic
    },
    beforeAvatarUpload2 (file) {
      const isJPG = file.type === 'image/jpeg'
      const isPNG = file.type === 'image/png'
      const isLt2M = file.size / 1024 / 1024 < 5

      if (!isJPG && !isPNG) {
        this.$message.error('上传详情图片只能是 JPG 和 PNG 格式!')
      }
      if (!isLt2M) {
        this.$message.error('上传详情图片大小不能超过 5MB!')
      }
      return (isJPG || isPNG) && isLt2M
    },
    // 价格库存
    rfdata (data) {
      if (data.specValS.length > 0) {
        let arr = []
        data.specValS.map(item => {
          let obj = {}
          obj[`id${data.id}`] = item.specVal
          return arr.push(obj)
        })
        return arr
      }
    },
    // 横
    getSpecValSArr (specData) {
      const arr = []
      var _this = this
      for (let i = 0, len = specData.length; i < len; i++) {
        if (_this.rfdata(specData[i])) {
          arr.push(_this.rfdata(specData[i]))
        }
      }
      return arr
    },
    // 纵
    // getSpecName (specData) {
    //   const columns = specData.map(item => {
    //     const perColumns = {
    //       title: item.specName,
    //       dataIndex: `id${item.id}`,
    //       key: `id${item.id}`
    //     }
    //     return perColumns
    //   })
    //   return columns
    // },
    // 纵 + 横
    refac (arr) {
      if (arr.length <= 1) return arr
      let arr1 = arr[0]
      let arr2 = arr[1]
      let index = 1

      return this.assembleData(arr, arr1, arr2, index)
    },
    assembleData (arr, arr1, arr2, index) {
      let arr3 = []

      for (let i = 0; i < arr1.length; i++) {
        for (let j = 0; j < arr2.length; j++) {
          arr3.push(Object.assign({}, arr1[i], arr2[j]))
        }
      }
      var _this = this
      if (arr[index + 1]) {
        return _this.assembleData(arr, arr3, arr[index + 1], index + 1)
      } else {
        return arr3
      }
    },
    submitForm () {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          alert('submit!')
        } else {
          console.log('error submit!!')
          return false
        }
      })
    }
  }
}
</script>

<style scoped lang="less">
  .containerBox{
    /deep/ .el-form > .el-form-item > label {
      padding-right:15px;
      color: #008fff;
    }
    .goodClass{
      display: inline-block;
      margin-bottom: 15px;
    }
    span{
      font-size:14px;
      color:#606266;
    }
    .goodClass:last-child{
      margin:0;
    }
    .goodClass /deep/ .el-select{
      margin-right:15px;
    }
    .goodClass /deep/ .el-select .el-input__inner{
      width:150px;
    }
    /deep/ .el-input--medium > .el-input__inner {
      width:200px;
    }
    /deep/ .el-button{
      color:#fff;
      background: #008fff;
      padding:10px;
    }

    .specB {
      /*width:800px;*/
      border: 1px solid #e5e5e5;
      -webkit-border-radius: 10px;
      -moz-border-radius: 10px;
      border-radius: 10px;
      padding:15px;
      margin-bottom: 15px;
      position: relative;
      /deep/ .el-form-item{
        margin-bottom: 10px;
      }
      .addBtn{
        display: inline-block;
        position: relative;
        /deep/ .el-input--medium  .el-input__inner{
          width:80px !important;
        }
        /deep/ .el-button{
          position: absolute;
          top:0;
          left:77px;
        }
      }
      .operations{
        position: absolute;
        top:10px;
        right:10px;
        a{
          margin-right:10px;
        }
      }
      .delSpec{
        color: #e95d6b;
      }

    }
    .specB:last-child{
      margin-bottom: 0;
    }

    .tags .el-select{
      margin-right:15px;
      margin-bottom: 15px;
      width:150px;
      /deep/ .el-input__inner{
        width:150px;
      }
    }
    span.specVal{
      line-height:34px;
      padding:0 10px;
      margin-right:10px;
      border:1px solid #e5e5e5;
      background: #fff;
      -webkit-border-radius: 5px;
      -moz-border-radius: 5px;
      border-radius: 5px;
      position: relative;
      .delBtn{
        position: absolute;
        width:15px;
        line-height:12px;
        -webkit-border-radius: 15px;
        -moz-border-radius: 15px;
        border-radius: 15px;
        background: orangered;
        color: #fff;
        text-align: center;
        height:15px;
        top:-5px;
        right:-5px;
      }
    }

    /deep/ .avatar-uploader {
      .el-upload {
        background: #fff;
        width: 200px;
        height:200px;
        border: 1px dashed #d9d9d9;
        border-radius: 6px;
        cursor: pointer;
        position: relative;
        overflow: hidden;
      }
      .avatar-uploader .el-upload:hover {
        border-color: #409EFF;
      }
      .avatar-uploader-icon {
        font-size: 28px;
        color: #8c939d;
        width: 178px;
        height: 178px;
        line-height: 178px;
        text-align: center;
      }
      .flex{
        width:100%;
        height:100%;
      }
      .avatar {
        max-width: 100%;
        max-height: 100%;
        display: block;
      }
    }
    .tableList {
      /deep/ .el-table .cell {
        color: #000;
        font-weight: normal;
        text-align: center;
        line-height: 25px;
      }
      /deep/ .el-table__body-wrapper tbody tr * {
        font-size: 14px;
      }
      /deep/ .el-table__body-wrapper tbody tr td .cell .tagS {
        border: 1px solid #c7c7c7;
        padding: 5px;
        margin-bottom: 5px;
        margin-right: 5px;
      }
      /deep/ .el-table__body-wrapper tbody tr td .cell a.oper {
        color: #008fff;
      }
    }
  }
</style>
